export default {
	namespaced: true,
	state: () => ({
		// 购物车的数组，用来存储购物车中每个商品对象
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
	}),
	getters: {
		// 购物车商品总数
		total(state) {
			let c = 0;
			state.cart.forEach(item => c += item.goods_count)
			return c
		},
		// 计算勾选的商品总数量
		checkedCount(state) {
			return state.cart.filter(item => item.goods_state).reduce((pre, cur) => pre += cur.goods_count, 0)
		},
		// 计算总价格
		totalPrice(state) {
			return state.cart.filter(item => item.goods_state).reduce((pre, cur) => pre += cur.goods_count *
				cur.goods_price, 0).toFixed(2)
		}
	},
	mutations: {
		addToCart(state, goods) {
			// 判断购物车是否已存在商品
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id);
			if (!findResult) {
				state.cart.push(goods);
			} else {
				findResult.goods_count++
			}
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		updateGoodsState(state, goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id);
			if (findResult) {
				findResult.goods_state = goods.goods_state;
				this.commit('m_cart/saveToStorage')
			}
		},
		updateGoodsCount(state, goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id);
			if (findResult) {
				findResult.goods_count = goods.goods_count;
				this.commit('m_cart/saveToStorage')
			}
		},
		removeGoodsById(state, goods_id) {
			state.cart = state.cart.filter(item => item.goods_id !== goods_id)
			this.commit('m_cart/saveToStorage')
		},
		checkedAllState(state, ischecked) {
			state.cart.map(item => item.goods_state = ischecked);
			this.commit('m_cart/saveToStorage')
		}
	}
}
